package com.example.everying.interceptor;/*
 * 项目名称: everything
 * 文件名: JwtInterceptor
 * 作者: 张泽阳
 * 日期: 2025/5/16
 * 描述:
 */

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.system.UserInfo;
import com.alibaba.fastjson2.JSONObject;
import com.example.everying.constant.CacheConstants;
import com.example.everying.context.UserContext;
import com.example.everying.model.entity.user.UserEntity;
import com.example.everying.model.vo.user.LoginUser;
import com.example.everying.model.vo.user.UserInfoVo;
import com.example.everying.service.user.UserService;
import com.example.everying.utils.JwtUtils;
import com.example.everying.utils.QueryLocationUtil;
import com.example.everying.utils.RedisUtils;
import com.example.everying.utils.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.apache.kafka.common.security.auth.Login;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private QueryLocationUtil queryLocationUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        AntPathMatcher pathMatcher = new AntPathMatcher();

        String url = request.getRequestURI();
        List<String> excludePaths = Arrays.asList(
                "/wxlogin/login",
                "/wxlogin/register",
                "/wxlogin/updatePassword",
                "/wxlogin/sms/send",
                "/wxlogin/sms/verify",
                "/wxlogin/appWxLogin",
                "/user/bindeWx",
                "/admin/article/detail/**",
                "/activity/thumb/**/count",
//                "/activity/comment/**/comments",
                "/admin/login",
                "/pay/wx/payCallback",
                "/pay/wx/transferCallback",
                "/admin/article/page",
                "/admin/article/bannerList",
                "/favicon.ico",
                "/index.html"

        );

        String token = request.getHeader("Authorization");
        // 检查当前路径是否匹配任何排除模式
        for (String pattern : excludePaths) {
            if (pathMatcher.match(pattern,  url)) {
                // 评论接口解析token
                if (StringUtils.isNotEmpty(token)) {
                    String id = JwtUtils.tokenParse(token);
                    LoginUser userInfoVo  = redisUtils.getCacheObject( CacheConstants.LOGIN_TOKEN_KEY +id);
                    // 用户信息放到上下文中
                    UserContext.setUser(userInfoVo);
                    return true;
                }
                return true; // 放行
            }
        }


        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        response.setCharacterEncoding("utf-8");


        if (token != null) {
            boolean result = JwtUtils.verify(token);
            if (result) {
                String id = JwtUtils.tokenParse(token);
                if (id.isEmpty()){
                    return false;
                }
                //UserInfoVo user = userService.getUserById(id);
//                LoginUser user = redisUtils.getCacheObject(CacheConstants.LOGIN_TOKEN_KEY + id);
                LoginUser userInfoVo  = redisUtils.getCacheObject( CacheConstants.LOGIN_TOKEN_KEY +id);
                if (userInfoVo == null){
                    try {
                        JSONObject json = new JSONObject();
                        json.put("success", "false");
                        json.put("msg", "未获取到用户信息,认证失败，未通过拦截器");
                        json.put("code", "500");
                        response.getWriter().append(json.toJSONString());
                        log.error("认证失败，未通过拦截器======ip {}  ======  url: {}==>",  request.getRemoteAddr(),url);
                        return false;
                    } catch (Exception e) {
                        e.printStackTrace();
                        response.sendError(500);
                        return false;
                    }
                }
                // 用户信息放到上下文中
                UserContext.setUser(userInfoVo);
                return true;
            }
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            JSONObject json = new JSONObject();
            json.put("success", "false");
            json.put("msg", "认证失败，未通过拦截器");
            json.put("code", "500");
            response.getWriter().append(json.toJSONString());
            log.error("认证失败，未通过拦截器======ip {}  ======  url: {}==>",  request.getRemoteAddr(),url);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(500);
            return false;
        }
        return false;

    }



    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 请求完成后清理 ThreadLocal
        UserContext.clear();
    }
}
